<template>
  <el-container class='elheight'>
    <el-aside class='appTree'>
      <app-tree v-bind:tree-data="treeData"
                v-on:appTreeClick="treeClickHandle"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData"
                       @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>小区名称：<el-input placeholder="请输入小区名称"
                        v-model="queryData.communityName"
                        clearable
                        class="dzy-custom-input"></el-input>
            </div>
            <div>楼栋名称：<el-input placeholder="请输入楼栋名称"
                        v-model="queryData.buildingName"
                        clearable
                        class="dzy-custom-input"></el-input>
            </div>
            <div>楼栋长：<el-input placeholder="请输入楼栋长名称"
                        v-model="queryData.buildingLeaderName"
                        clearable
                        class="dzy-custom-input"></el-input>
            </div>
            <div>电话：<el-input placeholder="请输入电话"
                        v-model="queryData.buildingLeaderPhone"
                        clearable
                        class="dzy-custom-input"></el-input>
            </div>
            <div>
              <el-button @click="searchHandleClick"
                         type="primary"
                         icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>
        <el-main>
          <app-table :page-data="pageData"
                     :table-columns="tableColumns"
                     v-on:currentChange="handleCurrentChange"
                     v-on:handleCheckedRows="handleCheckedRows"
                     v-on:checkSingleRow="checkSingleRow"
                     v-on:changeSingleRow="changeSingleRow"
                     v-on:deleSingleRow="deleSingleRow" />
          <el-dialog :title="dialogTitle"
                     :visible.sync="dialogFormVisible"
                     :before-close="close"
                     :close-on-click-modal="false">
            <el-form :model="formData"
                     :rules="rules"
                     ref="formData"
                     :disabled="showOnly"
                     label-width="120px"
                     size="mini">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="网格"
                                prop="allGridIdArr">
                    <!-- <grid-cascader v-model="formData.allGridId"
                                   @changeGrid="handleGridCascader"></grid-cascader> -->
                    <div class="block">
                        <el-cascader placeholder="请选择"
                          :options="treeOption"
                          filterable
                          clearable
                          :props="gridIdProps"
                          v-model="formData.allGridIdArr"
                          @change="handleGridCascader">
                        </el-cascader>
                      </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="所属小区"
                                prop="communityId">
                    <el-select no-data-text="请选择"
                               v-model="formData.communityId"
                               @change="afterCommunityIdCheck"
                               placeholder="请选择所属小区">
                      <el-option v-for="(item, index) in communityData"
                                 :selected="index === 0"
                                 :key="item.id"
                                 :value="item.id"
                                 :label="item.name"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="楼栋"
                                prop="id">
                    <el-select v-model="formData.id"
                               clearable
                               placeholder="请选择"
                               @change="afterBuildingIdCheck">
                      <el-option v-for="(build,index) in buildingOptions"
                                 :key="index"
                                 :label="build.buildingName"
                                 :value="build.id"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="楼栋类型"
                                prop="buildingType">
                    <el-select filterable
                               v-model="formData.buildingType"
                               placeholder="请选择楼栋类型">
                      <el-option v-for="item in dictData.buildingType"
                                 :key="item.id"
                                 :value="item.code"
                                 :label="item.name"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="建筑面积（²）"
                                prop="buildingArea">
                    <el-input v-model="formData.buildingArea"
                              disabled
                              placeholder="请输入建筑面积"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="单元数"
                                prop="unitNum">
                    <el-input v-model="formData.unitNum"
                              disabled
                              type="number"
                              min="1"
                              placeholder="请输入单元数"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="户数"
                                prop="familyNum">
                    <el-input v-model="formData.familyNum"
                              disabled
                              type="number"
                              min="1"
                              placeholder="请输入户数"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="楼栋人数"
                                prop="peopleNum">
                    <el-input v-model="formData.peopleNum"
                              placeholder="请输入楼栋人数"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="楼栋长姓名"
                                prop="buildingLeaderName">
                    <el-input v-model="formData.buildingLeaderName"
                              placeholder="请输入楼长姓名"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="性别"
                                prop="gender">
                    <el-select v-model="formData.gender"
                               clearable
                               placeholder="请选择">
                      <el-option v-for="(item,index) in sexs"
                                 :key="index"
                                 :label="item.name"
                                 :value="item.code"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="民族"
                                prop="nation">
                    <el-select v-model="formData.nation"
                               clearable
                               placeholder="请选择">
                      <el-option v-for="(item,index) in nationOption"
                                 :key="index"
                                 :label="item.name"
                                 :value="item.code"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="政治面貌"
                                prop="politicalStatus">
                    <el-select v-model="formData.politicalStatus"
                               clearable
                               placeholder="请选择">
                      <el-option v-for="(item,index) in politicalStatusOption"
                                 :key="index"
                                 :label="item.name"
                                 :value="item.code"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="出生日期"
                                placeholder="请选择出生日期"
                                prop="birthday">
                    <el-date-picker v-model="formData.birthday"
                                    value-format="timestamp"
                                    format="yyyy 年 MM 月 dd 日"
                                    placeholder="选择日期时间"
                                    :picker-options="dataPickerBeforeTodayOptions">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="学历"
                                prop="educationArr">
                    <el-cascader v-model="formData.educationArr"
                                 placeholder="请选择"
                                 :options="educationOption"
                                 filterable
                                 clearable
                                 :props="dictProps">
                    </el-cascader>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="手机号码"
                                prop="buildingLeaderPhone">
                    <el-input v-model="formData.buildingLeaderPhone"
                              placeholder="请输入手机号"
                              autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="固定电话"
                                prop="telephone">
                    <el-input v-model="formData.telephone"
                              placeholder="请输入固定电话"
                              autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="所在地"
                                prop="address">
                    <el-input v-model="formData.address"
                              placeholder="请输入所在地"
                              autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="所在地详址"
                                prop="addressDetail">
                    <el-input v-model="formData.addressDetail"
                              placeholder="请输入所在地详址"
                              autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="选择经纬度"
                                prop="longitude">
                    <el-col :span="8">
                      <el-input v-model="formData.longitude"
                                :disabled="true"
                                placeholder="经度"></el-input>
                    </el-col>
                    <el-col :span="1"
                            style="text-align: center">-</el-col>
                    <el-col :span="7">
                      <el-input v-model="formData.latitude"
                                :disabled="true"
                                placeholder="纬度"></el-input>
                    </el-col>
                    <el-col :span="8">
                      <el-button type="text"
                                 :disabled="false"
                                 @click="openSimpleMap">从地图选择</el-button>
                    </el-col>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div v-if="!showOnly"
                 slot="footer"
                 class="dialog-footer">
              <el-button @click="cancel('formData')">取 消</el-button>
              <el-button type="primary"
                         @click="save('formData')">提 交</el-button>
            </div>
          </el-dialog>
          <el-dialog class="dialog-body-mini"
                     :visible.sync="showMap"
                     title="选择经纬度"
                     width="70%"
                     top="8vh"
                     :before-close="mapCancel">
            <edit-map v-if="showMap"
                      :mode="mapMode"
                      @appMapCallback="appMapCallback"
                      :target="mapTarget"></edit-map>
          </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import AppTree from '@/components/common/AppTree'
import BtnGroup from '@/components/BtnGroup'
import AppTable from '@/components/AppTable'
import EditMap from '@/components/EditMap'
import GridCascader from '@/components/GridCascader'
import CascaderTree from '@/components/CascaderTree'
import { getCaseAllGridIdByGridTreeData, isCommonDo } from '@/utils/CommonUtil'
import { findBuildingLeader, updateBuilding, deleteBuilding, createBuilding, findCommunityList, findBuildingList, getBuilding } from '@/http/FangWuGuanLiApi'
// import { createMapLocation } from '@/http/AppApi'
import { getUserGridTree } from '@/utils/SessionDataUtil'
import DictDataUtil from '@/utils/DictDataUtil'
import { validatePhone, validateMobile } from '@/utils/validate'
import { getDictDataOption } from '@/utils/getDictDataOption'
import { getAllRegion } from '@/utils/region'
export default {
  data () {
    return {
      tableData: [],
      pageData: {},
      formData: {},
      queryData: {},
      treeData: [],
      gridIdProps: {
        label: 'name',
        value: 'id'
      },
      treeOption: [],
      politicalStatusOption: [],
      nationOption: [],
      sexs: [],
      educationOption: [],
      dialogTitle: '1111',
      dialogFormVisible: false,
      currentSelectedData: [],
      showOnly: false,
      showMap: false,
      mapTarget: {},
      mapHackReset: false,
      mapMode: 'simple',
      communityData: [],
      dictData: {},
      dictProps: {
        label: 'name',
        value: 'code'
      },
      tableColumns: [
        { label: '小区名称', prop: 'communityName' },
        { label: '楼栋名称', prop: 'buildingName' },
        { label: '单元数', prop: 'unitNum' },
        { label: '楼栋长', prop: 'buildingLeaderName' },
        { label: '性别', prop: 'gender', formatter: this.genderFormatter },
        { label: '联系方式', prop: 'buildingLeaderPhone' }
      ],
      activeNames: ['1', '2'],
      buildingOptions: [],
      dataPickerBeforeTodayOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      rules: {
        allGridIdArr: [{
          required: true,
          message: '选择网格',
          trigger: 'blur'
        }],
        communityId: [{
          required: true,
          message: '请选择所属小区',
          trigger: 'blur'
        }],
        id: [{
          required: true,
          message: '请选择楼栋',
          trigger: 'blur'
        }],
        buildingType: [{
          required: true,
          message: '请选择楼栋类型',
          trigger: 'blur'
        }],
        buildingArea: [{
          required: false,
          message: '请输入建筑面积',
          trigger: 'blur'
        }],
        floorNum: [{
          required: false,
          message: '请输入楼层数',
          trigger: 'blur'
        }],
        unitNum: [{
          required: false,
          message: '请输入单元数',
          trigger: 'blur'
        }],
        familyNum: [{
          required: false,
          message: '请输入户数',
          trigger: 'blur'
        }],
        peopleNum: [{
          required: false,
          message: '请输入楼栋人数',
          trigger: 'blur'
        }],
        buildingLeaderName: [{
          required: true,
          message: '请输入楼长姓名',
          trigger: 'blur'
        }],
        gender: [{
          required: true,
          message: '请选择',
          trigger: 'blur'
        }],
        nation: [{
          required: true,
          message: '请选择',
          trigger: 'blur'
        }],
        politicalStatus: [{
          required: true,
          message: '请选择政治面貌',
          trigger: 'blur'
        }],
        birthday: [{
          required: true,
          message: '请选择出生日期',
          trigger: 'blur'
        }],
        educationArr: [{
          required: true,
          message: '请选择',
          trigger: 'blur'
        }],
        buildingLeaderPhone: [{
          validator: validatePhone,
          message: '请输入手机号',
          trigger: 'blur'
        }],
        telephone: [{
          validator: validateMobile,
          message: '请输入固定电话',
          trigger: 'blur'
        }],
        address: [{
          required: true,
          message: '请输入所在地',
          trigger: 'blur'
        }],
        addressDetail: [{
          required: true,
          message: '请输入所在地详址',
          trigger: 'blur'
        }],
        longitude: [{
          required: false,
          message: '选择经纬度',
          trigger: 'blur'
        }],
        latitude: [{
          required: true,
          message: '选择经纬度',
          trigger: 'blur'
        }]
      }
    }
  },
  components: {
    AppTree,
    BtnGroup,
    AppTable,
    GridCascader,
    EditMap,
    CascaderTree
  },
  mounted () {
    this.getTableData()
    this.getTreeData()
  },
  methods: {
    afterCommunityIdCheck (val) {
      if (val) {
        let param = { communityId: val }
        findBuildingList(param).then(resp => {
          if (resp.code && resp.code === '200') {
            this.buildingOptions = resp.data
          } else {
            return ''
          }
        })
      }
    },
    afterBuildingIdCheck (val) {
      if (val) {
        getBuilding(val).then(resp => {
          if (resp.code && resp.code === '200') {
            let data = resp.data
            let allGridId = this.formData.allGridId
            let communityId = this.formData.communityId
            this.formData = data
            this.formData.allGridId = allGridId
            this.formData.communityId = communityId
          }
        })
      }
    },
    genderFormatter (row, column) {
      let genderOption = getDictDataOption('性别')
      let resGender = ''
      for (let i = 0; i < genderOption.length; i++) {
        if (genderOption[i].code === row.gender) {
          resGender = genderOption[i].name
          break
        }
      }
      return resGender
    },
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.formData.education = this.formData.educationArr ? this.formData.educationArr.join(',') : ''
          if (this.formData) {
            this.beforeSubmit()
            if (this.formData.id) {
              updateBuilding(this.formData).then(resp => {
                if (resp.code && resp.code === '200') {
                  this.dialogFormVisible = false
                  this.$message({
                    type: 'success',
                    message: '操作成功'
                  })
                  this.getTableData()
                  this.cancel(formName)
                }
              })
            } else {
              createBuilding(this.formData).then(resp => {
                if (resp.code && resp.code === '200') {
                  this.dialogFormVisible = false
                  this.getTableData()
                  this.cancel(formName)
                  this.dialogFormVisible = false
                  this.$refs[formName].resetFields()
                }
              })
            }
          }
        }
      })
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            deleteBuilding(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    cancel (formName) {
      this.mapCancel()
      this.dialogFormVisible = false
      this.formData = {}
      this.buildingOptions = []
      this.showOnly = false
      this.$refs[formName].resetFields()
    },
    close () {
      this.mapCancel()
      this.dialogFormVisible = false
      this.formData = {}
      this.buildingOptions = []
      this.showOnly = false
      this.$refs['formData'].resetFields()
    },
    beforeSubmit () {
      if (this.formData.allGridIdArr && this.formData.allGridIdArr.length !== 0) {
        let liveIndex = this.formData.allGridIdArr.length - 1
        let liveData = {}
        liveData.id = this.formData.allGridIdArr[liveIndex]
        liveData.items = this.treeData
        liveData.isGetAllId = true
        this.formData.allGridId = getAllRegion(liveData)
      } else {
        this.formData.allGridId = ''
      }
      return true
    },
    mapCancel () {
      this.mapHackReset = false
      this.showMap = false
    },
    getTableData () {
      let param = this.queryData
      findBuildingLeader(param).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data) {
            this.pageData = data
            isCommonDo(this.pageData, this)
            if (this.pageData.items && this.pageData.items instanceof Array) {
              this.tableData = this.pageData.items
            }
          }
        } else {
          this.$message({
            type: 'info',
            message: resp.message
          })
          return ''
        }
      })
    },
    getTreeData () {
      let gridTree = getUserGridTree()
      if (gridTree && gridTree instanceof Array) {
        this.treeData = gridTree
        this.treeOption = gridTree
      }
    },
    getCommunityData (gridId) {
      if (gridId && gridId !== '') {
        let param = { likeAllGridId: gridId }
        findCommunityList(param).then(resp => {
          if (resp.code && resp.code === '200') {
            let data = resp.data
            if (data && data instanceof Array) {
              this.communityData = data
            }
          }
        })
      }
    },
    handleCurrentChange (val) {
      this.queryData.offset = (val - 1) * 10
      this.getTableData()
    },
    treeClickHandle (data) {
      this.queryData.offset = 0
      this.queryData.likeAllGridId = data.id
      this.getTableData()
      this.formData.allGridId = getCaseAllGridIdByGridTreeData(data)
      this.formData.allGridIdArr = this.formData.allGridId.split(',')
    },
    btnClickCallback (callbackData) {
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
        this.dialogTitle = callbackData.dialogTitle
        this.dialogFormVisible = true
        this.getDictData()
        this.politicalStatusOption = getDictDataOption('政治面貌')
        this.nationOption = getDictDataOption('民族')
        this.educationOption = getDictDataOption('学历')
        this.sexs = getDictDataOption('性别')
        if (callbackData.btnType === 'post') {
          this.showOnly = false
          this.buildingOptions = []
          this.formData = this.formData.allGridId ? this.formData : {}
        } else {
          this.formData = callbackData.rows[0]
          this.showOnly = callbackData.btnType === 'get'
          let regionData = {}
          regionData.id = this.formData.gridId
          regionData.items = this.treeData
          let gridIdArr = getAllRegion(regionData)
          this.$set(this.formData, 'allGridIdArr', gridIdArr)
          this.getCommunityData(this.formData.gridId)
          this.afterCommunityIdCheck(this.formData.communityId)
          let educationArr = this.formData.education !== '' && this.formData.education !== null ? this.formData.education.split(',') : []
          this.$set(this.formData, 'educationArr', educationArr)
        }
      }
    },
    checkSingleRow: function (callbackData) {
      getBuilding(callbackData.rows[0].id).then(resp => {
        if (resp.code && resp.code === '200') {
          callbackData.rows = [resp.data]
          this.btnClickCallback(callbackData)
        }
      })
    },
    changeSingleRow: function (callbackData) {
      getBuilding(callbackData.rows[0].id).then(resp => {
        if (resp.code && resp.code === '200') {
          callbackData.rows = [resp.data]
          this.btnClickCallback(callbackData)
        }
      })
    },
    deleSingleRow: function (callbackData) {
      getBuilding(callbackData.rows[0].id).then(resp => {
        if (resp.code && resp.code === '200') {
          callbackData.rows = [resp.data]
          this.btnClickCallback(callbackData)
        }
      })
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        getBuilding(rows[0].id).then(resp => {
          if (resp.code && resp.code === '200') {
            this.currentSelectedData = [resp.data]
            this.formData = resp.data
          }
        })
      } else {
        this.currentSelectedData = []
      }
    },
    appMapCallback (appMapInfo) {
      if (appMapInfo.lnglat) {
        this.formData.longitude = appMapInfo.lnglat.lng
        this.formData.latitude = appMapInfo.lnglat.lat
        this.showOnly = false
        this.showMap = false
      }
    },
    searchHandleClick () {
      this.queryData.offset = 0
      this.getTableData()
    },
    handleGetCommunityData (allGridId) {
      if (allGridId && allGridId instanceof Array && allGridId.length > 0) {
        let gridId = allGridId[allGridId.length - 1]
        this.getCommunityData(gridId)
      }
    },
    getDictData () {
      this.dictData.buildingType = DictDataUtil.getBuildingType()
    },
    handleGridCascader (data) {
      if (data) {
        this.communityData = []
        let arr = data
        this.handleGetCommunityData(arr)
      }
    },
    openSimpleMap () {
      this.mapMode = 'simple'
      this.showMap = true
      this.mapHackReset = true
    }
  }
}
</script>
<style scoped>
.el-form >>> .el-form-item__error {
  margin-top: 2px;
}
.el-form >>> .el-input__inner {
  height: 37px;
}
.el-form >>> .el-form-item__label {
  line-height: 37px;
}
.el-form >>> .el-cascader__label {
  line-height: 37px;
}
.cascader-tree >>> .cascader-tree-input {
  width: 80%;
}
</style>
